package com.zhb.zhbojbackendquestionservice.aop;

import com.zhb.zhbojbackendcommon.annotation.RateLimiter;
import com.zhb.zhbojbackendcommon.common.ErrorCode;
import com.zhb.zhbojbackendcommon.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class RateLimiterAspect {
    @Autowired
    private RedissonClient redissonClient;

    @Around("@annotation(rateLimiter)")
    public Object around(ProceedingJoinPoint joinPoint, RateLimiter rateLimiter) throws Throwable {
        String key = rateLimiter.key();
        int limit = rateLimiter.limit();
        int expire = rateLimiter.expire();

        RRateLimiter rLimiter = redissonClient.getRateLimiter(key);
        // 设置限流规则：每秒允许 limit 次请求
        rLimiter.trySetRate(RateType.OVERALL, limit, expire, RateIntervalUnit.SECONDS);

        // 尝试获取令牌
        boolean acquired = rLimiter.tryAcquire(1);
        if (!acquired) {
            log.warn("触发限流：key={}", key);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请求过于频繁，请稍后再试！");
        }
        return joinPoint.proceed();
    }
}